import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import { Col, Dropdown, Icon, Menu, Row } from 'antd';
import moment from 'moment';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import { getTimeDistance } from '@/utils/utils';
import 'moment/locale/zh-cn';
import styles from './Analysis.less';
import PageLoading from '@/components/PageLoading';
import { requestPromise } from '@/utils/request';
import { getWebPath } from '../../utils/request';

const IntroduceRow = React.lazy(() => import('./IntroduceRow'));
const SalesCard = React.lazy(() => import('./SalesCard'));
const TopSearch = React.lazy(() => import('./TopSearch'));
const PayedOrders = React.lazy(() => import('./PayedOrders'));
const ProportionSales = React.lazy(() => import('./ProportionSales'));
const OfflineData = React.lazy(() => import('./OfflineData'));
const DeviceComputer = React.lazy(() => import('./DeviceComputer'));

@connect(({ chart, loading }) => ({
  chart,
  loading: loading.effects['chart/fetch'],
}))
class Analysis extends Component {
  state = {
    salesType: 'all',
    currentTabKey: '',
    rangePickerValue: getTimeDistance('year'),
    customerRanking: [],
    userRegistNum: [],
  };

  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'chart/fetch',
      });
    });
    this.getOrderInfo();
    this.getOrderNum();
    this.getPayedOrders();
    this.getGrouponOrderInfo();
    this.getDrawInfo();
    this.getProductSaleNums();
    this.getOrderNumV1();
    this.getListForDevice();
    this.getListForComputer();
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'chart/clear',
    });
    cancelAnimationFrame(this.reqRef);
    clearTimeout(this.timeoutId);
  }

  handleChangeSalesType = e => {
    this.setState({
      salesType: e.target.value,
    });
  };

  handleTabChange = key => {
    this.setState({
      currentTabKey: key,
    });
  };

  handleRangePickerChange = rangePickerValue => {
    const { dispatch } = this.props;
    this.setState({
      rangePickerValue,
    });
    let startTime = null;
    let endTime = null;
    let info = '';
    if (rangePickerValue.length !== 0) {
      startTime = moment(rangePickerValue[0]).format('YYYY-MM-DD');
      endTime = moment(rangePickerValue[1]).format('YYYY-MM-DD');
      info = `${startTime} - ${endTime}`;
    }
    requestPromise(`${getWebPath()}sys/user/getOrderNum?timePlaceOrder=${info}`, {
      method: 'GET',
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          histogramDatas: res.data.orderNums,
          customerRanking: res.data.customerRanking,
        });
      }
    });
    const data = {
      type: 'all',
      createTime_BETWEEN: info,
    };
    // 平台用户注册数量
    requestPromise(`${getWebPath()}user/statisticsInfo/queryUserRegistNumByDate`, {
      method: 'POST',
      body: data,
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          userRegistNum: res.data,
          // customerRanking: res.data.customerRanking,
        });
      }
    });
  };

  selectDate = type => {
    this.setState({
      rangePickerValue: getTimeDistance(type),
    });
    const { rangePickerValue } = this.state;
    const time = getTimeDistance(type);
    const startTime = moment(time[0]).format('YYYY-MM-DD');
    const endTime = moment(time[1]).format('YYYY-MM-DD');
    const info = `${startTime} - ${endTime}`;
    const data = {
      type,
      createTime_BETWEEN: info,
    };
    requestPromise(`${getWebPath()}sys/user/getOrderNum?timePlaceOrder=${info}`, {
      method: 'GET',
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          histogramDatas: res.data.orderNums,
          customerRanking: res.data.customerRanking,
        });
      }
    });
    // 平台用户注册数量
    requestPromise(`${getWebPath()}user/statisticsInfo/queryUserRegistNumByDate`, {
      method: 'POST',
      body: data,
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          userRegistNum: res.data,
          // customerRanking: res.data.customerRanking,
        });
      }
    });
  };

  isActive = type => {
    const { rangePickerValue } = this.state;
    const value = getTimeDistance(type);
    if (rangePickerValue !== undefined) {
      if (!rangePickerValue[0] || !rangePickerValue[1]) {
        return '';
      }
      if (
        rangePickerValue[0].isSame(value[0], 'day') &&
        rangePickerValue[1].isSame(value[1], 'day')
      ) {
        return styles.currentDate;
      }
    }

    return '';
  };

  /**
   * 获取订单相关信息
   */
  getOrderInfo = () => {
    requestPromise(`${getWebPath()}sys/user/getOrderInfo`, {
      method: 'GET',
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          orderInfo: res.data,
        });
      }
    });
    const data = {
      type: 'all',
    };
    // 平台用户注册数量
    requestPromise(`${getWebPath()}user/statisticsInfo/queryUserRegistNumByDate`, {
      method: 'POST',
      body: data,
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          userRegistNum: res.data,
          // customerRanking: res.data.customerRanking,
        });
      }
    });
  };

  /**
   * 统计订单数量
   */
  getOrderNum = () => {
    requestPromise(`${getWebPath()}sys/user/getOrderNum`, {
      method: 'GET',
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          orderDatas: res.data.orderNums,
          orderNum: res.data.orderNum,
          histogramDatas: res.data.orderNums,
          customerRanking: res.data.customerRanking,
        });
      }
    });
  };

  /**
   * 统计待发货订单
   */
  getPayedOrders = () => {
    requestPromise(`${getWebPath()}sys/user/getOrderList`, {
      method: 'GET',
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          orders: res.data.orders,
        });
      }
    });
  };

  /**
   * 统计拼团订单相关
   */
  getGrouponOrderInfo = () => {
    requestPromise(`${getWebPath()}sys/user/getGrouponOrderInfo`, {
      method: 'GET',
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          grouponTotalPrice: res.data.grouponTotalPrice,
          grouponTodayPrice: res.data.grouponTodayPrice,
          grouponOrderNums: res.data.grouponOrderNums,
        });
      }
    });
  };

  /**
   * 统计抽奖次数相关
   */
  getDrawInfo = () => {
    requestPromise(`${getWebPath()}sys/user/getDrawInfo`, {
      method: 'GET',
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          drawTotal: res.data.drawTotal,
          drawPriceTotal: res.data.drawPriceTotal,
        });
      }
    });
  };

  /**
   * 统计抽奖次数相关
   */
  getProductSaleNums = () => {
    requestPromise(`${getWebPath()}sys/user/getProductSaleNum`, {
      method: 'GET',
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          productSaleDatas: res.data.productSaleDatas,
          youjiaoDatas: res.data.youjiaoDatas,
          jingxuanDatas: res.data.jingxuanDatas,
          zazhiDatas: res.data.zazhiDatas,
        });
      }
    });
  };

  /**
   * 统计订单数量
   */
  getOrderNumV1 = () => {
    requestPromise(`${getWebPath()}sys/user/getOrderNumV1`, {
      method: 'GET',
      // contentType: "application/x-www-form-urlencoded",
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          orderDatasv1: res.data.orderNumsv1,
        });
      }
    });
  };

  /* DeviceComputer 组件 的方法 */
  /* DeviceComputer 组件 的方法 */

  getListForDevice = rangePickerValueStr => {
    requestPromise(
      `${getWebPath()}/sys/log/statisticsInfo/getListForDevice?dateRange=${rangePickerValueStr ||
        ''}`,
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        let deviceName = [];
        if (res.deviceName) {
          if (res.deviceName.length > 20) {
            deviceName = res.deviceName.slice(0, 20);
          } else {
            deviceName = res.deviceName;
          }
        }
        this.setState({
          deviceList: res.deviceList,
          deviceName,
          AndroidDeviceVersionList: res.deviceVersionMap.filter(
            value => value.x.indexOf('Android') !== -1
          ),
          iOSDeviceVersionList: res.deviceVersionMap.filter(value => value.x.indexOf('iOS') !== -1),
        });
      }
    });
  };

  getListForComputer = rangePickerValueStr => {
    requestPromise(
      `${getWebPath()}/sys/log/statisticsInfo/getListForComputer?dateRange=${rangePickerValueStr ||
        ''}`,
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        this.setState({
          systemVersionData: res.data,
          browseData: res.browseData,
        });
      }
    });
  };

  deviceComputerIsActive = type => {
    const { deviceComputerRangePickerValue: rangePickerValue } = this.state;
    const value = getTimeDistance(type);
    if (rangePickerValue !== undefined) {
      if (!rangePickerValue[0] || !rangePickerValue[1]) {
        return '';
      }
      if (
        rangePickerValue[0].isSame(value[0], 'day') &&
        rangePickerValue[1].isSame(value[1], 'day')
      ) {
        return styles.currentDate;
      }
    }
    return '';
  };

  deviceComputerHandleRangePickerChange = rangePickerValue => {
    const { dispatch } = this.props;
    this.setState({
      deviceComputerRangePickerValue: rangePickerValue,
    });
    if (rangePickerValue instanceof Array && rangePickerValue.length === 2) {
      const str = `${rangePickerValue[0].format('YYYY-MM-DD')} - ${rangePickerValue[1].format(
        'YYYY-MM-DD'
      )}`;
      this.getListForDevice(str);
      this.getListForComputer(str);
    }
  };

  deviceComputerSelectDate = type => {
    const { dispatch } = this.props;
    const rangePickerValue = getTimeDistance(type);
    this.setState({
      deviceComputerRangePickerValue: rangePickerValue,
    });

    if (rangePickerValue instanceof Array && rangePickerValue.length === 2) {
      const str = `${rangePickerValue[0].format('YYYY-MM-DD')} - ${rangePickerValue[1].format(
        'YYYY-MM-DD'
      )}`;
      this.getListForDevice(str);
      this.getListForComputer(str);
    }
  };

  render() {
    const {
      rangePickerValue,
      salesType,
      currentTabKey,
      orderInfo,
      histogramDatas,
      userRegistNum,
      customerRanking,
      orderDatas,
      orderNum,
      orders,
      grouponTotalPrice,
      grouponTodayPrice,
      grouponOrderNums,
      drawTotal,
      drawPriceTotal,
      productSaleDatas,
      youjiaoDatas,
      jingxuanDatas,
      zazhiDatas,
      orderDatasv1,
      deviceList,
      deviceName,
      browseData,
      systemVersionData,
      AndroidDeviceVersionList,
      iOSDeviceVersionList,
      deviceComputerRangePickerValue,
    } = this.state;
    const { chart, loading } = this.props;
    const {
      visitData,
      visitData2,
      salesData,
      searchData,
      offlineData,
      offlineChartData,
      salesTypeData,
      salesTypeDataOnline,
      salesTypeDataOffline,
    } = chart;
    let salesPieData = productSaleDatas;
    if (salesType === 'all') {
      salesPieData = productSaleDatas;
    } else if (salesType === 'preschool') {
      salesPieData = youjiaoDatas;
    } else if (salesType === 'picture-books') {
      salesPieData = jingxuanDatas;
    } else if (salesType === 'magazine') {
      salesPieData = zazhiDatas;
    }
    const menu = (
      <Menu>
        <Menu.Item>操作一</Menu.Item>
        <Menu.Item>操作二</Menu.Item>
      </Menu>
    );

    const dropdownGroup = (
      <span className={styles.iconGroup}>
        <Dropdown overlay={menu} placement="bottomRight">
          <Icon type="ellipsis" />
        </Dropdown>
      </span>
    );
    const activeKey = currentTabKey || (offlineData[0] && offlineData[0].name);
    console.log(orderDatas);
    return (
      <GridContent>
        <Suspense fallback={<PageLoading />}>
          <IntroduceRow
            loading={loading}
            visitData={orderDatas}
            orderInfo={orderInfo}
            orderNum={orderNum}
            grouponTotalPrice={grouponTotalPrice}
            grouponTodayPrice={grouponTodayPrice}
            grouponOrderNums={grouponOrderNums}
            drawTotal={drawTotal}
            drawPriceTotal={drawPriceTotal}
          />
        </Suspense>
        <Suspense fallback={null}>
          <SalesCard
            rangePickerValue={rangePickerValue}
            salesData={histogramDatas}
            userRegistNum={userRegistNum}
            customerRanking={customerRanking}
            isActive={this.isActive}
            handleRangePickerChange={this.handleRangePickerChange}
            loading={loading}
            selectDate={this.selectDate}
          />
        </Suspense>
        <Row gutter={24}>
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <Suspense fallback={null}>
              <PayedOrders
                loading={loading}
                visitData2={visitData2}
                // selectDate={this.selectDate}
                searchData={orders}
                dropdownGroup={dropdownGroup}
              />
            </Suspense>
          </Col>
          {/*用不着注释掉不要删除  后期万一要用到*/}
          {/*<Col xl={12} lg={24} md={24} sm={24} xs={24}>*/}
          {/*  <Suspense fallback={null}>*/}
          {/*    <TopSearch*/}
          {/*      loading={loading}*/}
          {/*      visitData2={visitData2}*/}
          {/*      selectDate={this.selectDate}*/}
          {/*      searchData={searchData}*/}
          {/*      dropdownGroup={dropdownGroup}*/}
          {/*    />*/}
          {/*  </Suspense>*/}
          {/*</Col>*/}
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <Suspense fallback={null}>
              <ProportionSales
                dropdownGroup={dropdownGroup}
                salesType={salesType}
                loading={loading}
                salesPieData={salesPieData}
                handleChangeSalesType={this.handleChangeSalesType}
              />
            </Suspense>
          </Col>
        </Row>
        {/*<Suspense fallback={null}>
          <OfflineData
            activeKey={activeKey}
            loading={loading}
            offlineData={offlineData}
            offlineChartData={orderDatasv1}
            handleTabChange={this.handleTabChange}
          />
        </Suspense>*/}

        {/*设备和PC访问统计*/}
        <Suspense fallback={null}>
          <DeviceComputer
            deviceList={deviceList}
            deviceName={deviceName}
            systemVersionData={systemVersionData}
            browseData={browseData}
            AndroidDeviceVersionList={AndroidDeviceVersionList}
            iOSDeviceVersionList={iOSDeviceVersionList}
            isActive={this.deviceComputerIsActive}
            rangePickerValue={deviceComputerRangePickerValue}
            handleRangePickerChange={this.deviceComputerHandleRangePickerChange}
            selectDate={this.deviceComputerSelectDate}
            loading={loading}
            // activeKey={activeKey}
            // offlineData={offlineData}
            // offlineChartData={orderDatasv1}
            // handleTabChange={this.handleTabChange}
          />
        </Suspense>
      </GridContent>
    );
  }
}

export default Analysis;
